package com.acoreful.acf2admin.test.rabbitmq;

import java.util.Arrays;


import org.apache.thrift.TSerializer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Produces AMQP Messages on the "com.berico.notifications"
 * channel after serializing a message (using the Thrift API).
 * @author Richard C. (Berico Technologies)
 */
public class MessageProducer {

  //The Queue we will be consuming
  public static String QUEUE_NAME = "com.berico.notifications";
  //The Host of the RabbitMQ
  public static String HOST = "localhost";
 
  public static void main(String... args){
  
    //Create an instance of our Domain object.
    //Keep in mind this is a Thrift generated bean.
   /* Notification notification = new Notification(
      1, 
      Arrays.asList(new String[]{ "richard", "john" }), 
      "Test Message", 
      "Hope this finds you well", 
      System.currentTimeMillis());*/
    Notification notification = new Notification(
    		1, 
    		Arrays.asList(new String[]{ "richard", "john" }), 
    		"Test Message", 
    		"Hope this finds you well", 
    		System.currentTimeMillis());
  
      try {
  
        //Create a connection factory
        ConnectionFactory factory = new ConnectionFactory();
        //Set the host to the location of the RabbitMQ server
        factory.setHost(HOST);
        //Open a new connection
        Connection connection = factory.newConnection();
        //Channel is the abstraction for interacting with a queue
        Channel channel = connection.createChannel();
        //Create the Queue if it does not exist
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
      
        //Create a new instance of the Thrift Serializer
        TSerializer serializer = new TSerializer();
        //Serialize our domain object to a byte array
        byte[] payload = serializer.serialize(notification);
      
        //Do this 10 times
        for(int i = 0; i < 10; i++){
       
          //Publish message on the queue using our domain
          //object as the message (or payload)
          channel.basicPublish("", QUEUE_NAME, null, payload);
       
          //Print a friendly message
          System.out.println(
             " [x] Sent '" 
             + notification.toString() + "'");
        }
      
        //Close the channel
        channel.close();
        //Close the connection
        connection.close();
      
      } catch (Exception e) {
        //Dump any exception to the console
        e.printStackTrace();
      } 
   }
}